from collections import Counter
import numpy as np

class Vocab(object):
    def __init__(self, label_counter):
        self._id2label = []

        for label, count in label_counter.most_common():
            self._id2label.append(label)

        reverse = lambda x: dict(zip(x, range(len(x))))
        self._label2id = reverse(self._id2label)

        self._label2id = reverse(self._id2label)
        if len(self._label2id) != len(self._id2label):
            print("serious bug: label dumplicated, please check!")
        
        print("Labels:", self._id2label)
        print("Vocab info: #label %d" % (self.label_size) )

    def label2id(self, xs):
        if isinstance(xs, list):
            return [self._label2id.get(x) for x in xs]
        return self._label2id.get(xs)

    def id2label(self, xs):
        if isinstance(xs, list):
            return [self._id2label[x] for x in xs]
        return self._id2label[xs]

    @property
    def label_size(self):
        return len(self._id2label)

def createVocab(train_instances):
    label_counter = Counter()
    label_counter['neg'] += 1
    label_counter['pos'] += 1
    vocab = Vocab(label_counter)
    return vocab